<template>
    <div>
        <!-- 顶部卡片全局组件Category -->
        <Category :scene="scene"></Category>
        <!-- 底部卡片 -->
        <el-card style="margin: 10px 0;">
           <div v-show="scene==0">
                <el-button @click="addAttr" type="primary" icon="Plus" :disabled="useCategroystore.c3Id?false:true">添加属性</el-button>
                <el-table border style="margin: 10px 0;" :data="attrArr">
                    <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
                    <el-table-column label="属性名称" width="150px" prop="name"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template # = "{row}">
                            <el-tag  style="margin: 5px;"
                                v-for="(item) in row.cateporyAttrList" 
                                :key="item.id">
                                {{ item.name }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{row}">
                            <el-button @click="updateAttr(row)" icon="Edit" size="small" type="primary"></el-button>
                            
                            <el-popconfirm title="您确定删除这个属性?" @confirm="AttrDelete(row)">
                                <template #reference>
                                    <el-button icon="Delete" size="small" type="danger"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
           </div>
           <div v-show="scene==1">
            <el-form :inline="true">
                <el-form-item label="属性名称">
                    <el-input placeholder="请输入属性名称" v-model="addAttrParmas.name"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="addAttrValue()" type="primary" icon="Plus" :disabled="addAttrParmas.name?false:true">添加</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
            <el-table border :data="addAttrParmas.cateporyAttrList">
                <el-table-column label="序号" type="index" width="80px"></el-table-column>
                <el-table-column label="属性值名称">
                    <template #="{row,$index}">
                        <el-input :ref="(vc:any)=>arrInput[$index]=vc" v-if="row.flag===true" @blur="lookAttr(row,$index)" placeholder="请输入标签值" v-model="row.name"></el-input>
                        <div v-else @dblclick="editAttr(row,$index)">{{ row.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="属性值操作">
                    <template #="{$index}">
                        <el-button @click="()=>addAttrParmas.cateporyAttrList.splice($index,1)" type="danger" icon="Delete" size="small"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="save" type="primary" :disabled="addAttrParmas.cateporyAttrList.length>0?false:true">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
           </div>
        </el-card>
    </div>
</template>

<script setup lang='ts'>
import { reqAttr ,reqaddOrUpdateAttr,reqDeleteAttr} from '@/api/product/attr';
import useCategroyStore from '@/store/modules/Category';
import type {ResponseCateproyAttr,ResponseAttrData,CateproyResponseData,CateproyObj} from '../../../api/product/attr/type' 
import { nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';

const useCategroystore=useCategroyStore()
//存储属性与属性值
const attrArr=ref<ResponseAttrData[]>([])
//控制属性展示与属性添加切换
const scene=ref(0)

//存储新增属性
let addAttrParmas=reactive<ResponseAttrData>({
    name:'',
    parentId:'',
    cateporyAttrList:[],
})
//存储输入框的ref
const arrInput=reactive<any>([])
//用于监控仓库三级分类id数据变化
watch(()=>useCategroystore.c3Id,()=>{
    // 清空上一次数据
    attrArr.value=[]
    //保证三级数据有才能发送请求
    if(!useCategroystore.c3Id) return 
    getAttr()
    
})
// 获取已有的属性和属性值的方法
const getAttr=async ()=>{
    const {c1Id,c2Id,c3Id}=useCategroystore
    const result:ResponseCateproyAttr=await reqAttr(c1Id,c2Id,c3Id)
    attrArr.value=result.data
}
//添加属性按钮
const addAttr=()=>{
    //每次点击的时候，先清空之前数据再收集
    Object.assign(addAttrParmas,{
        id:null,
        name:'',
        parentId:'',
        cateporyAttrList:[]
    })
    scene.value=1
    //收集三级分类id
    addAttrParmas.parentId=useCategroystore.c3Id
}
//修改属性按钮
const updateAttr=(row:CateproyObj)=>{
    scene.value=1
    //进行对象合并,JSON用于进行深拷贝
    Object.assign(addAttrParmas,JSON.parse(JSON.stringify(row)))
}
//取消按钮回调
const cancel=()=>{
    scene.value=0
}
//点击添加属性值按钮事件
const addAttrValue=()=>{
    addAttrParmas.cateporyAttrList.push({
        name:'',
        flag:true
    })
    nextTick(()=>{
        arrInput[arrInput.length-1].focus()
    })
}
//保存按钮
const save=async()=>{
    //发送请求
    const result:CateproyResponseData=await reqaddOrUpdateAttr(addAttrParmas)
    if(result.code===200){
        //回到属性展示页
        scene.value=0
        //成功弹窗
        ElMessage({
            type:'success',
            message:addAttrParmas.id?'修改成功':'添加成功'
        })
        //重新获取属性信息
        getAttr()
    }else{
        ElMessage({
            type:'success',
            message:addAttrParmas.id?'修改失败':'添加失败'
        })
    }
}
//进入查看模式
const lookAttr=(row:CateproyObj,$index:number)=>{
    // 非法情况一，判断输入是否为空或为空格
    if(row.name.trim()==''){
        //删除该项
        addAttrParmas.cateporyAttrList.splice($index,1)
        ElMessage({
            type:'error',
            message:'属性值不能为空'
        })
        return   
    }
    //非法情况二，判断重复
    const repeat=addAttrParmas.cateporyAttrList.find((item)=>{
        // 确保当前检查的元素不是row本身
        if(item!=row){
            // 检查当前元素的名称是否和row的名称相同,如果是就返回当前元素，不是就返回undefined
            return item.name===row.name   
        }
    })
    if(repeat){
        ElMessage({
            type:'error',
            message:'属性值不能重复'
        })
        addAttrParmas.cateporyAttrList.splice($index,1)
        return
    }
    
    row.flag=false
}
//双击进入编辑模式
const editAttr=(row:CateproyObj,$index:number)=>{
    //相应的属性值对象falg：变为true，展示input
    row.flag=true
    //nextTick：响应式数据发生变化，获取更新的DOM（组件实例
    nextTick(()=>{
        arrInput[$index].focus()
    })
}
//删除属性按钮
const AttrDelete=async (row:CateproyObj)=>{
    let result:CateproyResponseData=await reqDeleteAttr((row.id as number))
    if(result.code===200){
        //成功弹窗
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        //重新获取属性信息
        getAttr()
    }else{
        ElMessage({
            type:'success',
            message:'删除失败'
        })
    }

}

onBeforeUnmount(()=>{
    //清空属性仓库数据
    useCategroystore.$reset()
})

</script>

<style scoped lang='scss'>

</style>